package com.hnust.controller;

import com.hnust.domain.*;
import com.hnust.domain.Class;
import com.hnust.service.PaperResultService;
import com.hnust.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Yjx
 * @Data: 2021/12/11 19:33
 * @Version 1.0
 * @Project_Name: exam-master
 * @describe
 */
@CrossOrigin("*")
@RestController
@RequestMapping("/api/paperResult")
public class PaperResultController {
    @Autowired
    PaperResultService paperResultService;

    @GetMapping("/getClassName")
    public Result<List<ClassNameAndID>> getClassName(@RequestParam("examId") String examId){
        try{
            System.out.println(examId);
            List<TestMajorAndGrade> major = paperResultService.getMajor(examId);
            List<Class> classId = paperResultService.getClassId(major.get(0).getTestMajid(),major.get(0).getTestGrade());
            String majorName = paperResultService.getMajorName(major.get(0).getTestMajid());
            List<ClassNameAndID> list = new ArrayList<>();
            for(Class str:classId){
                list.add(new ClassNameAndID(str.getClaId(),str.getGrade()+"级"+majorName+str.getClaNumber()+"班"));
            }
            return new Result<List<ClassNameAndID>>(1,"成功",list);
        }catch (Exception e){
            return new Result<List<ClassNameAndID>>(0,e.getMessage(),null);
        }
    }

    //获取一个班级在某场考试学生的成绩
    @GetMapping("/getClassGrade")
    public Result<List<StudentGradReport>> getStudentGradReport(
            @RequestParam("examId") String examId,
            @RequestParam("classId") String classId){
        try{
            List<StudentGradReport> list = new ArrayList<>();
            List<Student> studentByClassId = paperResultService.getStudentByClassId(classId);
            for(Student student:studentByClassId){
                String studentScore=null;
                try {
                    studentScore = paperResultService.getStudentGrade(examId, student.getAccount());
                }catch (Exception e){}
                list.add(new StudentGradReport(student.getAccount(),student.getName(),null,studentScore));
            }
            return new Result<>(1,"成功",list);

        }catch (Exception e){
            return new Result<List<StudentGradReport>>(0,e.getMessage(),null);
        }
    }

    @GetMapping("/getTestName")
    public Result<String> getTestName(@RequestParam("testid") String testid) {
        try {
            String testName = paperResultService.getTestName(testid);
            return new Result<>(1,"成功",testName);
        } catch (Exception e) {
            return new Result<>(0,"失败",e.getMessage());
        }
    }

    @GetMapping("/getPaperDocx")
    public void getPaperDocx(HttpServletRequest request , HttpServletResponse response, @RequestParam("paperId") String paperId ) throws IOException {
        getFile(request,response,paperId,"paper");
    }

    /*
     * @Author Tonited
     * @Description //TODO 获取文件的工具方法
     * @Date 9:47 2020/10/31
     * @Param type{"example","paper","pdf","plan","answer"}
     * @return
     **/
    private void getFile(HttpServletRequest request , HttpServletResponse response, String fileName, String type) throws IOException {
        String typeTile = null;
        if("pdf".equals(type)){
            typeTile = "pdf";
        }else{
            typeTile="docx";
        }
        File file = new File(System.getProperty("user.dir") + "/assets/"+type);
        if(!file.exists()) {

            file.mkdir();
        }
        String filePath = System.getProperty("user.dir") + "/assets/"+type+"/"+fileName+"."+typeTile;
        response.setCharacterEncoding("UTF-8");
        fileName = URLEncoder.encode(fileName,"UTF-8");
        response.setHeader("Content-disposition", "attachment; filename="+fileName+"."+typeTile);
        //根据路径获取文件
        File docFile = new File(filePath);
        //获取文件后缀名格式
        String ext = docFile.getName().substring(docFile.getName().indexOf("."));
        //判断图片格式,设置相应的输出文件格式
        if(ext.equals("jpg")){
            response.setContentType("image/jpeg");
        }else if(ext.equals("JPG")){
            response.setContentType("image/jpeg");
        }else if(ext.equals("png")){
            response.setContentType("image/png");
        }else if(ext.equals("PNG")){
            response.setContentType("image/png");
        }else if(ext.toLowerCase().equals("doc")){
            response.setContentType("application/msword");
        }else if(ext.toLowerCase().equals("docx")){
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        }
        //读取指定路径下面的文件
        InputStream in = new FileInputStream(docFile);
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        //创建存放文件内容的数组
        byte[] buff =new byte[1024];
        //所读取的内容使用n来接收
        int n;
        //当没有读取完时,继续读取,循环
        while((n=in.read(buff))!=-1){
            //将字节数组的数据全部写入到输出流中
            outputStream.write(buff,0,n);
        }
        //强制将缓存区的数据进行输出
        outputStream.flush();
        //关流
        outputStream.close();
        in.close();
    }
}
